<template>
  <div class="article">
    <div class="head">
      <div class="head_l">
        <div class="returnBtn" @click="goBack(1)">
          <image src="/static/images/stationInfo/icon_return@2x.png" alt="" mode="widthFix"></image>
        </div>
        <div class="article_title">{{ answerList.exaParper.parperName }}</div>
      </div>

      <div class="head_r">
        <!-- <div class="timeOut">
          距本次考试时间结束还有：{{ remainingTimeIng.minutes }} 分 {{ remainingTimeIng.seconds }} 秒
        </div> -->
      </div>
    </div>

    <div class="articleDetail">
      <!-- 答题区 - 在 scroll-view 上添加 scroll-with-animation="true" -->
      <scroll-view scroll-y class="flex" @scroll="handleScroll" :scroll-into-view="scrollToViewId"
        scroll-with-animation="true">
        <div id="top-of-content"></div> <!-- 用于“返回顶部”按钮的滚动目标 -->
        <div class="detailContent" v-for="(item, classIndex) in answerList.exaClassVoList" :key="classIndex">
          <!-- 大标题 -->
          <div class="answer_title">
            <div class="answer_title_l">{{ item.exaParperClass.className }}</div>
            <div class="answer_title_r">共{{ item.exaClassQuestionsList.length }}题/总计{{
              getTotalScore(item.exaClassQuestionsList) }}分</div>
          </div>

          <div class="answer_content" v-for="(item2, questionIndex) in item.exaClassQuestionsList" :key="questionIndex"
            :id="'question-' + getQuestionGlobalIndex(classIndex, questionIndex)"
            :class="{ highlight: highlightedQuestionGlobalIndex === getQuestionGlobalIndex(classIndex, questionIndex) }">
            <!-- 题目 -->
            <div class="answer_content_title">
              <div class="answer_content_title_l">
                <span>{{ getQuestionGlobalIndex(classIndex, questionIndex) + 1 }}.</span>
                <span style="margin-left: calc(100vw * 10 / 2560);">
                  {{ item2.exaQuestionBankVo.exaQuestionBank.title }}
                </span>
              </div>
              <div class="answer_content_title_r">（{{ item2.exaQuestionBankVo.exaQuestionBank.score }}分）</div>
            </div>

            <div class="imgs" v-if="item2.exaQuestionBankVo.exaQuestionBank.type == 4">
              <image :src="baseUrl + item2.exaQuestionBankVo.exaQuestionBank.images" mode="widthFix"
                @tap="previewImage(item2.exaQuestionBankVo.exaQuestionBank.images)"></image>
            </div>

            <!-- 答案选项 -->
            <div class="box2" v-for="(option, oIndex) in item2.exaQuestionBankVo.exaQuestionOptionsList" :key="oIndex">
              <div class="answer_content_options" v-if="item2.exaQuestionBankVo.exaQuestionBank.type != 4">

                <div class="box">
                  <div class="daAn_txt">
                    {{ String.fromCharCode(65 + oIndex) }}： {{ option.content }}
                  </div>

                  <div class="dui">
                    <image
                      :src="option.selected ? '/static/images/index/icon_mark.svg' : '/static/images/index/icon_mark_nor.svg'"
                      mode="widthFix">
                    </image>
                  </div>
                </div>


              </div>

              <div class="jianda" v-if="item2.exaQuestionBankVo.exaQuestionBank.type == 4">
                <textarea v-model="option.content" class="textarea-custom" placeholder="请输入内容..." disabled
                  placeholder-style="color: rgba(255, 255, 255, 0.5);"
                  :maxlength="item2.exaQuestionBankVo.exaQuestionBank.maxString"
                  @input="handleJiandaInput($event, option)"></textarea>
              </div>
            </div>

            <!-- 显示正确答案 -->
            <div class="correctAnswer" v-if="item2.exaQuestionBankVo.exaQuestionBank.type != 4">
              <span>正确答案：</span>
              <span style="color: #FFD700;">
                {{
                  item2.exaQuestionBankVo.exaQuestionOptionsList
                    .map((option, oIndex) => option.rorw ? String.fromCharCode(65 + oIndex) : '')
                    .filter(v => v)
                    .join('、')
                }}
              </span>
            </div>

          </div>

        </div>
      </scroll-view>

      <!-- 答题卡区域 - 保持不变，作为 articleDetail 的右侧子元素 -->
      <div class="answerCard">
        <div class="answerCard_title">答题信息</div>
        <div class="answerCard_content">
          <div v-for="(item, index) in allQuestions" :key="index"
            :class="['answerCard_item', isQuestionAnswered(item) ? 'active_answerCard_item' : '']"
            @click="scrollToQuestion(index, item)">
            {{ index + 1 }}
          </div>
        </div>
      </div>

    </div>

    <div class="returnTop" :class="{ show: showTopBtn }" @click="goTop">
      <div class="topTxt">Top</div>
    </div>

  </div>
</template>

<script>
import { getParperInfo } from "@/api/index"
import config from '@/config.js'
// 正确引入组件
import uTextarea from 'uview-ui/components/u-textarea/u-textarea.vue'
import uButton from 'uview-ui/components/u-button/u-button.vue'

export default {
  // 添加性能优化配置
  options: {
    styleIsolation: 'shared'
  },
  components: {
    uTextarea,
    uButton
  },
  data() {
    return {
      baseUrl: '', // 基础URL
      // 答题列表
      answerList: {
        exaClassVoList: [],
        exaParper: {},
      },

      form: {},
      urlData: {}, // 接收的参数
      showTopBtn: false, // 是否显示返回顶部按钮
      open: false,
      open2: false,
      scrollToViewId: '', // 用于 scroll-into-view
      highlightedQuestionGlobalIndex: -1, // 用于高亮显示当前滚动到的题目
    }
  },

  onLoad(options) {
    console.log('答题页接收到的参数:', options);
    this.urlData = options;
    this.baseUrl = config.baseUrl

  },

  mounted() {
    this.baseUrl = config.baseUrl
    // 获取文章列表
    if (this.urlData.parperId) {
      this.getData();
    }
  },



  // 优化数据观察
  computed: {
    questionOptions() {
      return this.answerList?.exaClassVoList || [];
    },

    // 获取所有题目列表
    allQuestions() {
      let questions = [];
      if (Array.isArray(this.answerList?.exaClassVoList)) {
        this.answerList.exaClassVoList.forEach(classVo => {
          if (Array.isArray(classVo?.exaClassQuestionsList)) {
            questions = [...questions, ...classVo.exaClassQuestionsList];
          }
        });
      }
      return questions;
    }
  },

  methods: {
    // 获取试卷列表
    getData() {
      getParperInfo({
        parperId: this.urlData.parperId,
        bitchId: this.urlData.bitchId,
        userId: this.urlData.userId
      }).then(res => {
        console.log('试卷详情:', res);

        const data = JSON.parse(JSON.stringify(res.data));

        data.exaClassVoList.forEach(classVo => {
          classVo.exaClassQuestionsList.forEach(question => {
            question.exaQuestionBankVo.exaQuestionOptionsList.forEach(option => {
              if (question.exaQuestionBankVo.exaQuestionBank.type == 4) {
                this.$set(option, 'oldContent', option.oldContent || '');
                this.$set(option, 'content', option.oldContent || '');
                // 只要 oldContent 不是空字符串，selected 就为 true，否则为 false
                this.$set(option, 'selected', option.oldContent !== undefined && option.oldContent !== null && option.oldContent !== '');
              } else {
                this.$set(option, 'oldQuestion', option.oldQuestion || false);
                this.$set(option, 'selected', !!option.oldQuestion);
              }
            });
          });
        });
        this.answerList = data;
      });
    },

    // 计算大题总分方法
    getTotalScore(questionsList) {
      return questionsList.reduce((total, question) => {
        return total + (question.exaQuestionBankVo.exaQuestionBank.score || 0);
      }, 0);
    },

    // 获取题目在所有题目中的全局索引
    getQuestionGlobalIndex(classIndex, questionIndex) {
      let globalIndex = 0;
      for (let i = 0; i < classIndex; i++) {
        globalIndex += this.answerList.exaClassVoList[i].exaClassQuestionsList.length;
      }
      return globalIndex + questionIndex;
    },

    // 滚动到指定题目
    scrollToQuestion(globalIndex, question) {
      this.scrollToViewId = 'question-' + globalIndex;
      this.highlightedQuestionGlobalIndex = globalIndex; // 设置高亮索引
      setTimeout(() => {
        this.highlightedQuestionGlobalIndex = -1; // 2秒后移除高亮
      }, 2000);
    },

    // 预览图片
    previewImage(imgUrl) {
      uni.previewImage({
        urls: [this.baseUrl + imgUrl], // 需要预览的图片链接列表
        current: this.baseUrl + imgUrl, // 当前显示图片的链接
        indicator: 'number', // 显示页码
        loop: true, // 循环预览
        success: () => {
          console.log('图片预览成功');
        },
        fail: (err) => {
          console.error('图片预览失败:', err);
        }
      });
    },

    cancel() {
      this.open = false;
    },

    cancel2() {
      this.open2 = false;
      this.goBack(2); // 返回并提交状态为时间结束
    },


    // 检查题目是否已答
    isQuestionAnswered(question) {
      if (!question?.exaQuestionBankVo) return false;

      const questionType = question.exaQuestionBankVo.exaQuestionBank.type;
      const options = question.exaQuestionBankVo.exaQuestionOptionsList;

      // 简答题特殊处理
      if (questionType === 4) {
        return options?.some(option => {
          // 检查content是否存在且不为空
          return option.content && option.content.trim().length > 0;
        });
      }

      // 选择题处理
      return options?.some(option => option.selected === true);
    },


    goBack(status) {

      // 返回上一页并传递需要刷新的标志
      uni.navigateBack({
        delta: 1,
        success: () => {
          if (status) {
            this.doSubmit(status);
          }

          // 获取页面实例并调用方法
          const pages = getCurrentPages();
          const prevPage = pages[pages.length - 2]; // 获取上一页实例
          if (prevPage && prevPage.$vm) {
            // 调用上一页的刷新方法
            prevPage.$vm.getUserPaperList();
          }
        },
        fail: (err) => {
          console.error('返回失败:', err);
          // 如果返回失败，跳转到首页
          uni.switchTab({
            url: '/pages/index',
            success: () => {
              // 获取首页实例并调用刷新方法
              const pages = getCurrentPages();
              const indexPage = pages[pages.length - 1];
              if (indexPage && indexPage.$vm) {
                indexPage.$vm.getUserPaperList();
              }
            }
          });
        }
      });
    },

    goTop() {
      this.scrollToViewId = 'top-of-content'; // 滚动到顶部元素
      this.$nextTick(() => {
        this.scrollToViewId = ''; // 清除 ID 以便下次点击能再次触发滚动
      });
    },

    // 监听 scroll-view 的滚动事件
    handleScroll(e) {
      // 滚动超过 400px 显示按钮
      const scrollTop = e.detail.scrollTop;
      this.showTopBtn = scrollTop > 400;
    },
  }
}
</script>

<style lang="scss" scoped>
/deep/ .custom-tab-bar-wrapper {
  display: none !important;
}

.imgs {
  width: 100%;
  margin: calc(100vw * 20 / 2560) 0;

  image {
    width: 100%;
    height: auto;
    border-radius: calc(100vw * 8 / 2560);
  }
}

.article {
  width: 100vw;
  height: 100vh;
  background-color: #00063A;

  .head {
    width: 100vw;
    height: calc(100vw * 140 / 2560); // 高度按比例自适应
    background: url('@/static/images/index/bg_top2.png') no-repeat center center;
    background-size: cover;

    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 calc(100vw * 60 / 2560);
    box-sizing: border-box;

    .head_l {
      display: flex;
      justify-content: flex-start;
      align-items: center;

      .returnBtn {
        width: calc(100vw * 64 / 2560);
        height: calc(100vw * 64 / 2560);
        margin-right: calc(100vw * 30 / 2560);

        image {
          width: 100%;
          height: 100%;
        }
      }

      .article_title {
        font-size: calc(100vw * 40 / 2560);
        color: #FFFFFF;
        text-align: left;
      }
    }

    .head_r {
      font-size: calc(100vw * 40 / 2560);
      color: #FFFFFF;
      text-align: left;
    }

  }

  .articleDetail {
    width: calc(100vw * 2500 / 2560);
    height: calc(100vh - calc(100vw * 140 / 2560) - calc(100vw * 80 / 2560));
    margin: calc(100vw * 40 / 2560) calc(100vw * 30 / 2560);
    background: url('@/static/images/stationInfo/bg_articleList@2x.png');
    border-radius: calc(100vw * 24 / 2560);
    padding: calc(100vw * 80 / 2560) calc(100vw * 260 / 2560);
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
  }

  .flex {
    width: calc(100vw * 1420 / 2560);
    height: 100%;
    min-height: 100%;
    padding-bottom: calc(100vw * 120 / 2560);
    display: flex;
    flex-direction: column;
    gap: calc(100vw * 80 / 2560);
    align-items: stretch;
    box-sizing: border-box;
    -webkit-overflow-scrolling: touch;
  }

  .detailContent {
    width: 100%;
    color: #fff;
    height: auto;
    padding-right: calc(100vw * 68 / 2560);
    box-sizing: border-box;
    display: flex;
    flex-direction: column;

    .answer_title {
      width: 100%;
      height: calc(100vw * 81 / 2560);
      background: linear-gradient(180deg, #3670FF 0%, #1022D5 100%);
      border-radius: calc(100vw * 12 / 2560);
      font-size: calc(100vw * 32 / 2560);
      padding: calc(100vw * 18 / 2560) calc(100vw * 60 / 2560);
      box-sizing: border-box;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .answer_title_r {
        min-width: calc(100vw * 100 / 2560);
      }
    }

    .answer_content {
      width: 100%;
      height: auto;
      // min-height: calc(100vw * 1000 / 2560);
      // border: #fff solid 1px;
      margin-top: calc(100vw * 48 / 2560);
      display: flex;
      flex-direction: column; // 垂直方向
      gap: calc(100vw * 20 / 2560); // 增加垂直间距
      padding: calc(100vw * 20 / 2560) calc(100vw * 60 / 2560);
      box-sizing: border-box;

      &:last-child {
        margin-bottom: calc(100vw * 80 / 2560); // 最后一个元素增加更大的底部外边距
      }

      .answer_content:last-child {
        margin-bottom: calc(100vw * 180 / 2560); // 最后一个答题内容增加底部外边距
      }

      &.highlight {
        animation: bgFlash 3s linear infinite;
        border-radius: calc(100vw * 12 / 2560);
        box-sizing: border-box;
      }

      .answer_content_title {
        width: 100%;
        min-height: calc(100vw * 80 / 2560); // 改为最小高度
        font-size: calc(100vw * 32 / 2560);
        display: flex;
        justify-content: flex-start;
        align-items: flex-start;
        color: #fff;
        padding: calc(100vw * 18 / 2560) 0;
        box-sizing: border-box;

        .answer_content_title_l {
          width: 95%;
          height: auto;
          word-wrap: break-word;
          word-break: break-all;
          white-space: normal;
          line-height: 1.4;
          padding-top: 0;
          margin-top: 0;
        }

        .answer_content_title_r {
          min-width: calc(100vw * 160 / 2560);
          align-self: flex-start; // 分数靠顶对齐
          padding-top: 0;
          margin-top: 0;
          // margin-right: calc(100vw * 30 / 2560);
        }
      }

      .box2 {

        .jianda {
          width: calc(100vw * 1200 / 2560);
          background: #0B165C;
          border-radius: calc(100vw * 8 / 2560);
          border: 2px solid rgba(251, 251, 251, 0.2);
          padding: calc(100vw * 20 / 2560);
          box-sizing: border-box;
          margin-top: calc(100vw * 20 / 2560);

          .textarea-custom {
            width: 100%;
            min-height: calc(100vw * 200 / 2560);
            background: transparent;
            color: #fff;
            font-size: calc(100vw * 32 / 2560);
            line-height: 1.5;
            padding: calc(100vw * 10 / 2560);
            box-sizing: border-box;
          }
        }

        .answer_content_options {
          width: calc(100vw * 1200 / 2560);
          background: #0B165C;
          border-radius: calc(100vw * 8 / 2560);
          border: 2px solid rgba(251, 251, 251, 0.2);
          padding: calc(100vw * 20 / 2560);
          box-sizing: border-box;
          font-size: calc(100vw * 40 / 2560);
          display: flex;
          justify-content: space-between;
          align-items: center;

          .box {
            width: calc(100vw * 1200 / 2560);
            height: auto;
            display: flex;
            justify-content: space-between;
            align-items: center;

            .daAn {
              width: calc(100vw * 1015 / 2560);
              height: auto;
              word-wrap: break-word; // 允许长单词或 URL 地址换行到下一行
              word-break: break-all; // 允许在单词内换行
              white-space: normal; // 空白会被忽略，文本会换行
              line-height: 1.4; // 适当的行高
              padding: calc(100vw * 5 / 2560) 0; // 添加上下内边距
            }

            .dui {
              min-width: calc(100vw * 48 / 2560);
              min-height: calc(100vw * 48 / 2560);

              image {
                width: 100%;
                height: 100%;
              }
            }
          }


        }
      }

      .correctAnswer {
        font-size: calc(100vw * 32 / 2560);
        color: #fff;
      }

    }

  }

  .answerCard {
    width: calc(100vw * 560 / 2560);
    height: auto;
    color: #fff;

    .answerCard_content {
      width: 100%;
      height: auto;
      max-height: 100%;
      overflow: hidden;
      overflow-y: scroll;
      padding: calc(100vw * 20 / 2560) 0;
      box-sizing: border-box;
      display: flex;
      justify-content: flex-start;
      flex-wrap: wrap;
      gap: calc(100vw * 20 / 2560); // 增加间距

      .answerCard_item {
        width: calc(100vw * 56 / 2560);
        height: calc(100vw * 56 / 2560);
        line-height: calc(100vw * 56 / 2560);
        background: #FFFFFF;
        border-radius: 8px 8px 8px 8px;
        border: 2px solid #707070;
        color: #000;
        font-size: calc(100vw * 32 / 2560);
        text-align: center;
      }

      .active_answerCard_item {
        background: #6974BE;
        color: #fff;
      }
    }
  }

  /* 以下样式保持不变 */
  .submitBtn {
    position: fixed;
    bottom: calc(100vw * 80 / 2560);
    left: 50%;
    transform: translateX(-50%);
    height: calc(100vw * 120 / 2560);
    display: flex;
    justify-content: center;
    align-items: center;
    width: calc(100vw * 480 / 2560);
    font-size: calc(100vw * 48 / 2560);
    color: #FFFFFF;
    background: linear-gradient(180deg, #FF7171 0%, #BE1212 100%);
    box-shadow: inset 0px 0px 9px 1px #1C0007;
    border-radius: 99px 99px 99px 99px;
    z-index: 999;
  }

  .returnTop {
    position: fixed;
    bottom: calc(100vw * 60 / 2560);
    right: calc(100vw * 60 / 2560);
    width: calc(100vw * 70 / 2560);
    height: calc(100vw * 70 / 2560);
    box-shadow: 0px;
    background: rgba(54, 112, 255, 0.2);
    border-radius: calc(100vw * 15 / 2560);
    display: flex;
    justify-content: center;
    align-items: center;
    opacity: 0; // 默认透明
    visibility: hidden; // 默认隐藏
    transition: opacity 0.3s ease, visibility 0.3s ease, background-color 0.3s ease;
    z-index: 998;

    &.show {
      opacity: 1;
      visibility: visible;
      animation: bgFlash 3s linear infinite; // 添加闪烁动画
    }

    .topTxt {
      font-size: calc(100vw * 26 / 2560);
      color: #FFFFFF;
      text-align: center;
    }

    &:hover {
      background-color: rgba(54, 112, 255, 0.4); // 鼠标悬停时变色
    }
  }

  .mask {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba($color: #000114, $alpha: 0.6);
    z-index: 9999;
    display: flex;
    justify-content: center;
    align-items: center;

    .submitAnswer {
      width: calc(100vw * 1024 / 2560);
      height: calc(100vw * 540 / 2560);
      background: url('@/static/images/index/bg_answer.png') no-repeat center center;
      background-size: cover;
      background-color: transparent;
      padding: 0 calc(100vw * 80 / 2560);
      box-sizing: border-box;
      z-index: 1000;
      color: #fff;
      position: fixed;
      bottom: 30%;
      left: 50%;
      transform: translateX(-50%);
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: center;

      .top {
        font-size: calc(100vw * 48 / 2560);
        color: #FFFFFF;
        text-align: center;
        padding-top: calc(100vw * 15 / 2560);
        box-sizing: border-box;
      }

      .center {
        width: calc(100vw * 863 / 2560);
        height: calc(100vw * 183 / 2560);
        ;
        font-size: calc(100vw * 40 / 2560);
        color: #FFFFFF;
        line-height: calc(100vw * 64 / 2560);
        text-align: left;
      }

      .bottom {
        width: 100%;
        height: calc(100vw * 120 / 2560);
        display: flex;
        justify-content: space-around;
        align-items: center;

        uni-button {
          width: calc(100vw * 230 / 2560);
          height: calc(100vw * 80 / 2560);
          border-radius: calc(100vw * 40 / 2560);
          font-size: calc(100vw * 32 / 2560) !important;
          border: none;
        }

        // bottom 里第一个按钮的样式
        :first-child {
          background: linear-gradient(180deg, #3670FF 0%, #1022D5 100%);
          box-shadow: inset 0px 0px 9px 1px #1C0007;
        }

        :last-child {
          background: linear-gradient(180deg, #FF7171 0%, #BE1212 100%);
          box-shadow: inset 0px 0px 9px 1px #1C0007;
          text-align: center;
        }
      }
    }
  }
}

// 添加闪烁动画关键帧
@keyframes bgFlash {
  0% {
    background-color: transparent;
  }

  16.7% {
    background-color: rgba(54, 112, 255, 0.2); // 使用半透明的主题色
  }

  33.3% {
    background-color: transparent;
  }

  50% {
    background-color: rgba(54, 112, 255, 0.2);
  }

  66.7% {
    background-color: transparent;
  }

  83.3% {
    background-color: rgba(54, 112, 255, 0.2);
  }

  100% {
    background-color: transparent;
  }
}
</style>
